import { ElMessage } from 'element-plus';
import _ from 'lodash-es';
import { defineStore } from 'pinia';
import { storeToRefs } from 'pinia';
import { getPersonalInformation } from '@/apis/api-user';
import { clearToken } from '@/utils/auth';
import useSystemStore from './storeSystem.js';

const useUserStore = defineStore('storeOther', {
  state: () => ({
    number: 0,
    role: 'admin',
    userInfo: null,
    businessMap: [],
  }),

  actions: {
    addNumber() {
      this.number += 1;
    },
    subtractNumber() {
      this.number -= 1;
    },
    // 存储当前用户信息
    STORE_USER_BUSINESS(value) {
      this.businessMap = value;
    },

    // 存储当前用户信息
    STORE_USER_INFO(userInfo) {
      this.userInfo = userInfo;

      this.CURRENT_USER_ROLE(userInfo.roles);
    },

    // 当前用户所拥有的权限
    CURRENT_USER_ROLE(value) {
      const systemStore = useSystemStore();
      const { systemPermission } = storeToRefs(systemStore);

      if (value?.length) {
        const permissions = value
          ?.map((item) => {
            return item.permissions;
          })
          .filter((value) => value !== undefined)
          .reduce(function (a, b) {
            return a.concat(b);
          })
          .filter(function (item, index, self) {
            return self.findIndex((el) => el.id == item.id) === index;
          })
          ?.map((v) => {
            return v.title;
          });
        const systemPermissionAll = _.cloneDeep(systemPermission.value);

        for (var key in systemPermissionAll) {
          if (permissions.includes(key)) {
            systemPermissionAll[key] = true;
          } else {
            systemPermissionAll[key] = false;
          }
        }

        this.STORE_USER_BUSINESS(systemPermissionAll);
      } else {
        this.STORE_USER_BUSINESS(systemPermission.value);
      }
    },

    // 获取当前登录人信息
    async SELECT_LOGIN_CURRENT() {
      try {
        const [err, data] = await getPersonalInformation();

        if (!err) {
          this.STORE_USER_INFO(data.data);
        }
      } catch (error) {
        ElMessage({
          type: 'warning',
          message: '获取用户信息失败, 请重新登录',
        });
        clearToken();

        return Promise.reject(error);
      }
    },
  },
});

export default useUserStore;
